from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse


import os
import subprocess
import uuid

from datetime import datetime

from utils.FileUtil import fetch_file
from configs import config
from pdf2zh import pdf2zh

router = APIRouter(prefix="/pdf", tags=["论文翻译"])


@router.post("/translate")
async def translate(request: Request):
    data = await request.json()

    pdf_file = data.get("file")
    lang_in = data.get("lang_in")
    lang_out = data.get("lang_out")
    service = data.get("service")
    page = data.get("page")

    localdir = f"upload/{datetime.now().strftime('%Y-%m-%d')}"
    os.makedirs(f"{config.setting.statics.path}/{localdir}", exist_ok=True)
    localfile = f"{localdir}/{uuid.uuid4()}"

    fetch_file(pdf_file, f"{config.setting.statics.path}/{localfile}.pdf")

    try:
        pdf2zh.main(
            [
                f"{config.setting.statics.path}/{localfile}.pdf",
                "-o",
                f"{config.setting.statics.path}/{localdir}",
                "-s",
                "gitee",
                "-p",
                page,
                "-li",
                lang_in,
                "-lo",
                lang_out,
            ]
        )
    except subprocess.CalledProcessError as e:
        pass

    return JSONResponse(
        content={
            "data": {
                "url": f"{config.setting.statics.urls}/{localfile}-mono.pdf",
                "size": os.path.getsize(
                    f"{config.setting.statics.path}/{localfile}-mono.pdf"
                ),
            }
        }
    )
